package cn.xxstudy.blog.controller

import cn.xxstudy.blog.entity.Comment
import cn.xxstudy.blog.service.BlogService
import cn.xxstudy.blog.service.CommentService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.PageableDefault
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping

/**
 * 作者：xinxi on 2020/11/29 14:02
 * 包名：cn.xxstudy.blog.controller
 * TODO：博客
 */
@Controller
class BlogController {
    companion object {
        private const val BLOG_CONTENT = "blog"
        private const val BLOG_HISTORY = "history"
        private const val BLOG_COMMENT_LIST = "blog::commentList"
        private const val BLOG_COMMENT_REDIRECT = "redirect:/comment/"
        private const val ERROR_404 = "error/404"
    }

    @Autowired
    private lateinit var blogService: BlogService

    @Autowired
    private lateinit var commentService: CommentService

    @GetMapping("/blog/{id}")
    fun readBlog(@PathVariable id: Long, model: Model): String {
        val blog = blogService.getFormatBlog(id)
        blog?.let {
            model.addAttribute("blog", it)
            return BLOG_CONTENT
        }
        return ERROR_404
    }

    @GetMapping("/comment/{blogId}")
    fun comment(@PathVariable blogId: Long, model: Model): String {
        model.addAttribute("commentList", commentService.findListCommentByBlogId(blogId))
        return BLOG_COMMENT_LIST
    }

    @PostMapping("/comment")
    fun commentPost(comment: Comment): String {
        val id = comment.blog.id
        comment.blog = blogService.getBlog(id)
        comment.avatar = comment.blog.user.avatar
        commentService.saveComment(comment)
        return BLOG_COMMENT_REDIRECT + id
    }

    @GetMapping("/history")
    fun history(model: Model): String {
        model.addAttribute("historyMap", blogService.historyMap())
        model.addAttribute("blogCount", blogService.blogCount())
        return BLOG_HISTORY
    }
}